<?php
/**
 * Created by PhpStorm.
 * User: changshuiwang
 * Date: 2016/7/7
 * Time: 15:16
 */
namespace common\models;

use Yii;
use yii\base\Model;
use yii\base\Model\LoginForm;

/**
 * Login form
 */
class RegistForm extends User
{
    public $username;
    public $password;
    public $password2;
    public $rememberMe = true;
    public $type;

    private $_user;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username','password','password2'], 'required', 'on'=> 'regist'],
            ['username','unique','message'=>'用户名已占用','on'=>'regist'],
            ['password2', 'compare', 'compareAttribute'=>'password', 'message'=>'两次输入密码不一致','on'=>'regist'],
        ];
    }
    public function scenarios()
    {
        return [
            'regist' => ['username', 'password','password2'],
            //'update' => ['username'],
        ];
    }
    /**
     * Validates the user.
     *
     * @return boolean whether the user has registed
     */
/*    public function validateUsername($attribute,$params)
    {
        if(!$this->hasErrors()){
            if(User::findByUsername($this->username)!==null){
                $this->addError($attribute,"账号已注册");
            }
        }
    }*/
    /**
     *
     * 验证密码一致
     *
     * @param $password
     * @return boolean 两次密码一致为true
     */
/*    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            if ($this->password!=$this->password2) {
                $this->addError($attribute, '两次输入不一致.');
            }
        }
    }*/

    /**
     * Regist function
     *
     * @return boolean whether the user is logged in successfully
     */
    public function regist()
    {
        if ($this->validate()) {
            User::addUser($this->username,$this->password,$this->type);
            $id=Yii::$app->db->getLastInsertID();

            return $id;
        } else {
            return false;
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }
}
